<?php

namespace stlswm\WxSubscriptionPHP;

/**
 * Trait CurlHttp
 *
 * @package WxSubscriptionPHP
 */
trait CurlHttp
{
    public static $GetRequest = 1;
    public static $PostRequest = 2;

    /**
     * @param int    $requestType
     * @param string $url
     * @param mixed  $data
     * @param int    $timeout
     *
     * @return Response
     * @Author wm
     * @Date   2018/12/29
     * @Time   10:29
     */
    private static function curl(int $requestType, string $url, $data, int $timeout): Response
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        if ($requestType == self::$PostRequest) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        $errNo = curl_errno($ch);
        $errStr = curl_error($ch);
        curl_close($ch);
        $response = new Response();
        if ($errNo) {
            $response->result = false;
            $response->message = $errStr;
            return $response;
        }
        $resultArray = json_decode($result, true);
        if (!$resultArray) {
            $response->result = false;
            $response->message = 'api返回数据无法解析：' . $result;
            return $response;
        }
        if (!empty($resultArray['errcode'])) {
            $response->result = false;
            $response->errMsg = $response->message = isset($resultArray['errmsg']) ? $resultArray['errmsg'] : 'unknown';
            $response->errCode = $resultArray['errcode'];
            return $response;
        }
        $response->result = true;
        $response->data = $resultArray;
        return $response;
    }

    /**
     * @param string $url
     *
     * @return Response
     * @Author wm
     * @Date   2018/12/29
     * @Time   13:42
     */
    private static function get(string $url): Response
    {
        return self::curl(self::$GetRequest, $url, [], 60);
    }

    /**
     * @param string $url
     * @param mixed  $data
     *
     * @return Response
     * @Author wm
     * @Date   2018/12/29
     * @Time   13:42
     */
    private static function post(string $url, $data): Response
    {
        return self::curl(self::$PostRequest, $url, $data, 60);
    }

    /**
     * @param string          $url
     * @param array|\StdClass $data
     *
     * @return Response
     * @Author wm
     * @Date   2018/12/29
     * @Time   13:42
     */
    private static function postJson(string $url, $data): Response
    {
        return self::curl(self::$PostRequest, $url, json_encode($data), 60);
    }
}